package com.xiaomi.shwx.common.config;



import com.xiaomi.shwx.common.enums.WorkOrderEvents;
import com.xiaomi.shwx.common.enums.WorkOrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.EnumStateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;

import java.util.EnumSet;

/**
 * @author lei
 * @description 状态机配置类
 */
@EnableStateMachine(name="workOrderStateMachine")
@Configuration
@Slf4j
public class WorkOrderStateMachineConfig extends EnumStateMachineConfigurerAdapter<WorkOrderStatus, WorkOrderEvents> {

    /**
     * 配置状态
     * @param stateConfigurer
     * @throws Exception
     */
    @Override
    public void configure(StateMachineStateConfigurer<WorkOrderStatus, WorkOrderEvents> stateConfigurer) throws Exception {
        stateConfigurer.withStates()
                .initial(WorkOrderStatus.CREATE) // 初始状态
                .states(EnumSet.allOf(WorkOrderStatus.class)); // 所有状态
    }

    @Override
    public void configure(StateMachineTransitionConfigurer<WorkOrderStatus, WorkOrderEvents> transitions) throws Exception {
        transitions
                //创建工单 -> 工程师接单 -> 待用户确认
                .withExternal()
                .source(WorkOrderStatus.CREATE).target(WorkOrderStatus.BE_CONFIRM)
                .event(WorkOrderEvents.WORKER_ACCEPT_ORDER)
                .and()
                //待用户确认 -> 用户确认 -> 用户已确认
                .withExternal()
                .source(WorkOrderStatus.BE_CONFIRM).target(WorkOrderStatus.CONFIRM)
                .event(WorkOrderEvents.USER_CONFIRM_ORDER)
                .and()
                //用户已确认 -> 工程师检测 -> 检测
                .withExternal()
                .source(WorkOrderStatus.CONFIRM).target(WorkOrderStatus.CHECK)
                .event(WorkOrderEvents.WORKER_INSPECTION)
                .and()
                //检测 -> 申请物料维修 -> 复检
                .withExternal()
                .source(WorkOrderStatus.CHECK).target(WorkOrderStatus.RECHECK)
                .event(WorkOrderEvents.APPLICATION_MATERIALS_SUCCESS)
                .and()
                //等待工程师接单 -> 用户取消 -> 订单已取消
                .withExternal()
                .source(WorkOrderStatus.CREATE).target(WorkOrderStatus.CANCEL)
                .event(WorkOrderEvents.USER_CANCEL_ORDER)
        ;
    }

}
